/**
 * 存储辅助工具，提供可靠的存储机制，当主要存储机制失败时提供备选方案
 */

// 内存存储备份
const memoryStorage = {
  _data: {},
  setItem: function(key, value) {
    return new Promise((resolve) => {
      this._data[key] = value;
      resolve(value);
    });
  },
  getItem: function(key) {
    return new Promise((resolve) => {
      resolve(this._data[key] || null);
    });
  },
  removeItem: function(key) {
    return new Promise((resolve) => {
      delete this._data[key];
      resolve();
    });
  },
  clear: function() {
    return new Promise((resolve) => {
      this._data = {};
      resolve();
    });
  },
  keys: function() {
    return new Promise((resolve) => {
      resolve(Object.keys(this._data));
    });
  }
};

// 存储状态
let storageStatus = {
  isLocalStorageReady: false,
  useMemoryBackup: false
};

// 简单的localStorage封装，用于避免存储错误
const localStorageWrapper = {
  // 存储空间管理配置
  config: {
    maxSize: 4.5 * 1024 * 1024, // 最大存储容量4.5MB (localStorage通常限制为5MB)
    warningThreshold: 4 * 1024 * 1024, // 警告阈值4MB
    cleanupRatio: 0.2 // 清理20%的数据
  },
  
  // 获取当前localStorage使用量
  getStorageSize: function() {
    let total = 0;
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      const value = localStorage.getItem(key) || '';
      total += key.length + value.length;
    }
    return total * 2; // UTF-16编码，每个字符2字节
  },
  
  // 清理最旧的数据
  cleanupStorage: function() {
    try {
      // 仅处理聊天相关的键
      const chatKeys = [];
      const keyTimestamps = [];
      
      // 收集所有聊天相关的键
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (key.startsWith('chats-')) {
          chatKeys.push(key);
          
          // 提取时间戳（如果有）或使用默认值
          let timestamp = 0;
          try {
            const value = localStorage.getItem(key);
            if (value) {
              const data = JSON.parse(value);
              timestamp = data.lastSendTime || 0;
            }
          } catch (e) {
            // 忽略解析错误
          }
          
          keyTimestamps.push({
            key: key,
            timestamp: timestamp
          });
        }
      }
      
      if (chatKeys.length === 0) {
        return; // 没有可清理的键
      }
      
      // 按时间戳排序，最旧的在前面
      keyTimestamps.sort((a, b) => a.timestamp - b.timestamp);
      
      // 计算要删除的数量
      const removeCount = Math.max(1, Math.floor(chatKeys.length * this.config.cleanupRatio));
      
      // 删除最旧的数据
      for (let i = 0; i < removeCount; i++) {
        if (i < keyTimestamps.length) {
          localStorage.removeItem(keyTimestamps[i].key);
          console.log('存储空间清理: 删除旧数据', keyTimestamps[i].key);
        }
      }
      
      console.log(`存储空间清理完成: 删除了 ${removeCount} 项旧数据`);
    } catch (err) {
      console.warn('存储空间清理失败:', err);
    }
  },
  
  // 检查和管理存储空间
  checkStorageSpace: function() {
    try {
      const size = this.getStorageSize();
      
      // 如果超过警告阈值，记录警告
      if (size > this.config.warningThreshold) {
        console.warn(`localStorage使用量: ${(size / 1024 / 1024).toFixed(2)}MB，接近限制`);
      }
      
      // 如果超过最大容量，进行清理
      if (size > this.config.maxSize) {
        console.warn(`localStorage使用量: ${(size / 1024 / 1024).toFixed(2)}MB，超过安全阈值，执行清理`);
        this.cleanupStorage();
      }
      
      return size;
    } catch (err) {
      console.error('检查存储空间失败:', err);
      return 0;
    }
  },
  
  setItem: function(key, value) {
    return new Promise((resolve) => {
      try {
        // 检查存储空间
        this.checkStorageSpace();
        
        const stringValue = JSON.stringify(value);
        localStorage.setItem(key, stringValue);
        resolve(value);
      } catch (err) {
        console.warn('本地存储写入失败:', err);
        
        // 如果是存储空间不足的错误，尝试清理
        if (err.name === 'QuotaExceededError' || err.code === 22) {
          console.warn('存储空间不足，尝试清理旧数据');
          this.cleanupStorage();
          
          // 再次尝试存储
          try {
            const stringValue = JSON.stringify(value);
            localStorage.setItem(key, stringValue);
            resolve(value);
            return;
          } catch (e) {
            console.error('清理后仍无法保存数据:', e);
          }
        }
        
        resolve(null);
      }
    });
  },
  
  getItem: function(key) {
    return new Promise((resolve) => {
      try {
        const value = localStorage.getItem(key);
        if (value) {
          resolve(JSON.parse(value));
        } else {
          resolve(null);
        }
      } catch (err) {
        console.warn('本地存储读取失败:', err);
        resolve(null);
      }
    });
  },
  
  removeItem: function(key) {
    return new Promise((resolve) => {
      try {
        localStorage.removeItem(key);
      } catch (err) {
        console.warn('本地存储删除失败:', err);
      }
      resolve();
    });
  },
  
  keys: function() {
    return new Promise((resolve) => {
      try {
        const keys = [];
        for (let i = 0; i < localStorage.length; i++) {
          keys.push(localStorage.key(i));
        }
        resolve(keys);
      } catch (err) {
        console.warn('获取本地存储键名失败:', err);
        resolve([]);
      }
    });
  },
  
  clear: function() {
    return new Promise((resolve) => {
      try {
        localStorage.clear();
      } catch (err) {
        console.warn('清除本地存储失败:', err);
      }
      resolve();
    });
  }
};

// 初始化存储
export function initStorage() {
  try {
    // 尝试使用localStorage进行测试
    const testKey = '_test_storage_';
    localStorage.setItem(testKey, 'test');
    localStorage.removeItem(testKey);
    
    // 初始检查存储空间状态
    const size = localStorageWrapper.checkStorageSpace();
    console.log(`存储系统初始化成功，使用localStorage (当前使用: ${(size / 1024 / 1024).toFixed(2)}MB)`);
    
    storageStatus.isLocalStorageReady = true;
    storageStatus.useMemoryBackup = false;
    return Promise.resolve(true);
  } catch (err) {
    console.error('存储系统初始化失败，使用内存存储:', err);
    storageStatus.isLocalStorageReady = false;
    storageStatus.useMemoryBackup = true;
    return Promise.resolve(false);
  }
}

// 可靠的存储函数
export function safeSetItem(key, value) {
  if (storageStatus.useMemoryBackup) {
    // 如果使用内存备份，直接存到内存
    return memoryStorage.setItem(key, value);
  }
  
  // 尝试使用localStorageWrapper，失败时降级到内存存储
  return localStorageWrapper.setItem(key, value)
    .then((result) => {
      if (result === null) {
        storageStatus.useMemoryBackup = true;
        return memoryStorage.setItem(key, value);
      }
      return result;
    })
    .catch((err) => {
      console.warn(`无法保存到本地存储 [${key}], 使用内存存储:`, err);
      storageStatus.useMemoryBackup = true;
      return memoryStorage.setItem(key, value);
    });
}

// 可靠的获取函数
export function safeGetItem(key) {
  if (storageStatus.useMemoryBackup) {
    // 如果使用内存备份，直接从内存获取
    return memoryStorage.getItem(key);
  }
  
  // 尝试从localStorage读取，失败时从内存存储读取
  return localStorageWrapper.getItem(key)
    .then((value) => {
      if (value === null && memoryStorage._data[key]) {
        return memoryStorage.getItem(key);
      }
      return value;
    })
    .catch((err) => {
      console.warn(`无法从本地存储读取 [${key}], 尝试内存存储:`, err);
      return memoryStorage.getItem(key);
    });
}

// 可靠的删除函数
export function safeRemoveItem(key) {
  const promises = [
    localStorageWrapper.removeItem(key),
    memoryStorage.removeItem(key)
  ];
  
  return Promise.all(promises).then(() => true);
}

// 获取存储状态
export function getStorageStatus() {
  return { ...storageStatus };
}

// 导出统一的接口
export default {
  init: initStorage,
  setItem: safeSetItem,
  getItem: safeGetItem,
  removeItem: safeRemoveItem,
  getStatus: getStorageStatus
}; 